using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Collisions;
using StupidSpaceThing.MenuSystem;
using StupidSpaceThing;

namespace RacerGame
{
	internal class PlayerEntity : FlyingEntity
	{
		private static Model _model;
		public static void InitModel(Model model) {
			_model = model;
		}

		private GraphicsDevice device;
		private RenderTarget2D lifeTarget;
		public Quad LifeQuad;
		public PlayerIndex PlayerIndex;

		public PlayerEntity(Vector3 position)
			: base(_model, position, Quaternion.Identity, 0.0007f) {
			armor = 20;
			float radius = 2.0f;
			colObject = new ColCircle(this, 1, radius);			
			colObject.Geom.RestitutionCoefficient = .7f;
			colObject.Geom.FrictionCoefficient = 0.2f;
			colObject.Body.LinearDragCoefficient = 3.5f;
		}

		public void Init(GraphicsDevice device) {
			this.device = device;
			lifeTarget = new RenderTarget2D(device, 40, 40, 1, SurfaceFormat.Color, MultiSampleType.None, 0);
			LifeQuad = new Quad(null);
			LifeQuad.Scale = 3f;
			LifeQuad.Rotation = Matrix.CreateRotationX(-MathHelper.PiOver2);
		}

		public override void Update(RealGameTime gameTime) {
			Heal(0.06f);
			Rotate(0, 0.1f, 0);
			base.Update(gameTime);
		}

		public void UpdateLifeDraw() {			
			StupidSpaceThing.TextureTools.Begin(lifeTarget);
			string life = Life.ToString("N0");
			Vector2 lifeSize = RacerGame.SpriteFont.MeasureString(life);
			StupidSpaceThing.TextureTools.SpriteBatch.DrawString(RacerGame.SpriteFont, life, new Vector2(20 - lifeSize.X / 2, 0), GetLifeColor(), 0, Vector2.Zero, 1, SpriteEffects.None, 0);
			LifeQuad.Texture = StupidSpaceThing.TextureTools.End();
			LifeQuad.Position = Position + new Vector3(0, 7, 0);
		}

		public override void ApplyDamage(float damage, FactionEntity attacker) {
			TopMenu.Vibration[(int)PlayerIndex] += (damage / Armor) / 10.0f;
			base.ApplyDamage(damage, attacker);
		}

		public override void Die() {
			if( !Dead && !FactionEntity.Faction.Defeated && !RacerGame.Ended ) {
				foreach( KeyValuePair<PlayerIndex, Player> pair in RacerGame.Players ){
					if( pair.Value.Entity != this && !pair.Value.Entity.Dead ) {
						pair.Value.Score++;
					}
				}
			}
			base.Die();
		}
	}
}
